import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {FormBuilder, Validators} from '@angular/forms';
import {Command} from '../../../../shared/toolbar.service';
import {ModuleCodeService} from '../../../../service/module-code.service';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';

import {MyValidators} from '../../../../utils/validator/rang';
import {ModuleCode} from '../../../../entity/module-code.model';

@Component({
  selector: 'app-module-code-edit',
  templateUrl: './module-code-edit.component.html',
  styleUrls: ['./module-code-edit.component.css']
})
export class ModuleCodeEditComponent extends BladeContainerBase<ModuleCode> {
  colorOut: {};

  constructor(
    private fb: FormBuilder,
    private moduleCodeService: ModuleCodeService,
  ) {
    super(fb);
  }

  ngOnInit(): void {
    // 编辑时注册按钮和按钮命令
    if (!this.isNew) {
      this.commands = [
        // tslint:disable-next-line:max-line-length
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ];
    } else {
      this.currentEntity = new ModuleCode(0, '', '', '', 1, 0);
    }
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof TurbstatusValueListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    this.formPatchValue(this.currentEntity);
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  /**
   * 创建表单
   *
   *
   * @memberof DicKeyEditComponent
   */
  createForm() {
    this.formGroup = this.fromBuider.group({
      'name': [this.currentEntity.name, [
        Validators.required,
        Validators.pattern('^[\u4e00-\u9fa5a-zA-Z0-9]+$'),
        Validators.maxLength(50),
      ]],
      'descs': [this.currentEntity.descs, [
        Validators.required,
        Validators.pattern('^[A-Za-z0-9]+$'),
        Validators.maxLength(20)
      ]],
      'code': [this.currentEntity.code, [
        Validators.required,
        Validators.pattern('^[A-Za-z0-9]+$'),
      ]],
      'level': [this.currentEntity.level, [
        Validators.required,
        MyValidators.rang(0, 255)
      ]],
      'seq': [this.currentEntity.seq, [
        Validators.required,
        MyValidators.rang(0, 255)
      ]]
    });
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'name': '',
      'descs': '',
      'code': '',
      'level': '',
      'statusSeq': '',
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'name': {
        'required': '状态名称不能为空。',
        'pattern': '状态名称必须是汉字字母数字。',
        'maxlength': '状态名称不能多于50个字符长度。',
        'exist': '状态名称已存在。',
      },
      'code': {
        'required': '状态标识不能为空。',
        'pattern': '状态名称必须是英文数字组成。',
        'maxlength': '状态标识不能多于20个字符长度。',
        'exist': '状态标识已存在。',
      },
      'level': {
        'required': '请选择分类',
      },
      'seq': {
        'required': '排序值不能为空。',
        'rang': '排序值范围是0~255。',
      }
    };
  }

  /**
   * 创建一个风机状态
   *
   *
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.moduleCodeService.create(this.currentEntity)
        .then(res => {
          if (res.id) {
            const parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  /**
   *
   *
   *
   * @memberof TurbstatusEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent();
      return this.moduleCodeService.update(this.currentEntity)
        .then(res => {
          if (res) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  changeCurrent() {
    this.bladeData.isLoading = true;
    const formValue = this.formGroup.value as ModuleCode;
    this.currentEntity.name = formValue.name;
    this.currentEntity.descs = formValue.descs;
    this.currentEntity.code = formValue.code;
    this.currentEntity.level = formValue.level;
    this.currentEntity.seq = formValue.seq;
  }

  recPro(event: {}) {
    this.colorOut = event;
  }
}
